<template>
  <span>
    <el-button type="primary" @click="showDia=true">{{text}}</el-button>
    <el-dialog title="选择文件" width="420px" :visible.sync="showDia" modal-append-to-body append-to-body>
      <div v-loading="loading">
        <el-upload
          class="upload-import"
          ref="upload"
          action=""
          :on-change="handleChange"
          :on-remove="handleRemove"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          :auto-upload="false">
          <div class="button-box">
            <el-button size="small" type="primary">点击上传</el-button>
            <span slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</span>
          </div>
        </el-upload>

        <div class="footer">
          <el-button @click="showDia=false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="save.loading">{{save.defaultText}}</el-button>
        </div>
      </div>
    </el-dialog>
  </span>
</template>
<script>
  export default {
    props:{
      text:{ //按钮名称
        type: String,
        default: '导入'
      },
      /** fields格式 key为要显示的列内容，value为对应的字段名称
       * fields:{
       *  '登录名': 'loginname',
       *  '用户名': 'username',
       *  '手机号': 'phone'
       * }
       **/
      fields:{ //需要导出的数据和对应的字段
        type: Object,
        default: () => {return {}}
      },
    },
    data(){
      return{
        showDia: false,
        limitUpload: 1,
        fileListUpload: [],
        accountList: [],
        file: '',
        fileTemp: null,
        save:{
          loading: false,
          defaultText: '确定',
          text: '确定',
          loadingText: '正在解析数据...',
        },
        loading: false,
      }
    },
    watch:{
      showDia(val){
        if (!val){
          Object.assign(this.$data, this.$options.data())
          this.$refs.upload.clearFiles();
        }
      }
    },
    methods:{
      //上传文件时处理方法
      handleChange(file, fileList){
        this.loading = true
        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }
        this.fileTemp = file.raw;
        if(this.fileTemp){
          if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            || (this.fileTemp.type == 'application/vnd.ms-excel')){
            // this.loading = true
            let _this = this;
            setTimeout(() => {
              this.importExcel(_this.fileTemp);
            },100)
          } else {
            this.$message({
              type:'warning',
              message:'附件格式错误，请删除后重新上传！'
            })
            this.loading = false
          }
        } else {
          this.$message({
            type:'warning',
            message:'请上传附件！'
          })
          this.loading = false
        }
      },
      //移除文件的操作方法
      handleRemove(file,fileList){
        this.fileTemp = null
        this.accountList = []
      },
      importExcel(obj) {
        let _this = this;
        this.file = obj
        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;
        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function(e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for(var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            var XLSX = require('xlsx');
            if(rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                type: 'base64'
              });
            } else {
              wb = XLSX.read(binary, {
                type: 'binary'
              });
            }

            // outdata就是你想要的东西 excel导入的数据
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            const tHeader = Object.values(_this.fields); //对应表格输入的title
            const filterVal = Object.keys(_this.fields); // 对应表格输入的数据
            // excel 数据再处理
            let arr = []
            outdata.map(v => {
              let obj = {}
              filterVal.forEach((item,index) => {
                obj[item] = v[tHeader[index]]

              })
              arr.push(obj)
            })

            _this.accountList = [...arr];
            _this.loadedData()
            _this.loading = false
          }
          reader.readAsArrayBuffer(f);
        }

        if(rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }

      },
      submit(){
        if (!this.accountList.length){
          this.$message.error('没有可导入的数据，请先上传文件或检查上传文件内容是否为空。')
          return false;
        }
        this.$emit('upload',this.accountList)
        this.showDia = false
      },
      //解析列表数据中
      loadingData(){
        this.save.loading = true
        this.save.defaultText = this.save.loadingText
      },
      //数据解析结束
      loadedData(){
        this.save.loading = false
        this.save.defaultText = this.save.text
      },
    }
  }
</script>
<style lang="scss" scoped>
  .upload-import{
    .button-box{
      display: flex;
    }
  }
  .footer{
    text-align: right;
    margin-top: 20px;
  }
</style>
